<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2018/8/4
 * Time: 11:04
 */

namespace app\wx\controller;


use app\lib\exception\YouHaoTipException;
use app\wx\WxConfig;

class JsSdk extends WxConfig
{
    public function getSignPackage()
    {
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
//         $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
//        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $url = urldecode(input('url'));

        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);

        $signPackage = [
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string,
            "js_ticket" => $jsapiTicket,
            "access_token" => $this->getWxAccessToken()
        ];
        return json($signPackage);
    }

    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket()
    {
        //$token = '12_kJ2AKxHesLXmryVlmK1OXYGegERR3cxLikEi0X0UOdYJZ8SulN_oo7O5X5xlpLFgcWTltvExzMFlTxJd0eeK_R3Jv85_hbpyXOU0Tp3E5Ps3aI8Q1l5PK_MXJvfDBJhQ1UxeEAlXedl7NU30HHXaADACCS';
        if (!$this->getWxAccessToken()) {
//            throw new YouHaoTipException([
//                'code' => 200,
//                'msg' => 'access_token 不存在！！',
//                'errorCode' =>200
//            ]);
            echo json_encode([
                'code' => 2,
                'msg' => 'access_token 不存在！！'
            ]);
            die();
        }
        $token = $this->getWxAccessToken();
        $js = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $token . "&type=jsapi");
        $jss = json_decode($js, True);
        $ticket = $jss['ticket'];//   取出JS凭证, 至于存储代码就不列举了
        return $ticket;
    }

}